<template>
  <div class="create-subject">
    <TeacherNavbar title="创建科目" />
    
    <el-card class="form-card">
      <template #header>
        <div class="card-header">
          <span>科目信息</span>
        </div>
      </template>
      
      <el-form 
        :model="subjectForm" 
        :rules="rules" 
        ref="subjectForm" 
        label-width="180px" 
        class="subject-form">
        
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="科目名称" prop="subjectName">
              <el-input v-model="subjectForm.subjectName" placeholder="请输入科目名称"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="24">
            <h3 class="section-title">题型设置</h3>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="选择题数量" prop="choiceQuestionCount">
              <el-input-number 
                v-model="subjectForm.choiceQuestionCount" 
                :min="0" 
                :max="100" 
                label="选择题数量">
              </el-input-number>
            </el-form-item>
          </el-col>
          
          <el-col :span="12">
            <el-form-item label="选择题分值" prop="choiceQuestionScore">
              <el-input-number 
                v-model="subjectForm.choiceQuestionScore" 
                :min="0.5" 
                :max="10" 
                :step="0.5"
                label="选择题分值">
              </el-input-number>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="判断题数量" prop="judgmentQuestionCount">
              <el-input-number 
                v-model="subjectForm.judgmentQuestionCount" 
                :min="0" 
                :max="100" 
                label="判断题数量">
              </el-input-number>
            </el-form-item>
          </el-col>
          
          <el-col :span="12">
            <el-form-item label="判断题分值" prop="judgmentQuestionScore">
              <el-input-number 
                v-model="subjectForm.judgmentQuestionScore" 
                :min="0.5" 
                :max="10" 
                :step="0.5"
                label="判断题分值">
              </el-input-number>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="填空题数量" prop="fillQuestionCount">
              <el-input-number 
                v-model="subjectForm.fillQuestionCount" 
                :min="0" 
                :max="100" 
                label="填空题数量">
              </el-input-number>
            </el-form-item>
          </el-col>
          
          <el-col :span="12">
            <el-form-item label="填空题分值" prop="fillQuestionScore">
              <el-input-number 
                v-model="subjectForm.fillQuestionScore" 
                :min="0.5" 
                :max="20" 
                :step="0.5"
                label="填空题分值">
              </el-input-number>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="考试时长(分钟)" prop="timeLimit">
              <el-input-number 
                v-model="subjectForm.timeLimit" 
                :min="10" 
                :max="180" 
                label="考试时长">
              </el-input-number>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="24">
            <div class="summary-section">
              <el-alert
                :title="summaryText"
                type="info"
                show-icon
                :closable="false">
              </el-alert>
            </div>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item class="form-actions">
              <el-button 
                type="primary" 
                @click="submitForm" 
                :loading="submitting"
                size="large">
                {{ submitting ? '创建中...' : '创建科目' }}
              </el-button>
              <el-button @click="resetForm" size="large">重置</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import TeacherNavbar from '@/components/TeacherNavbar.vue'
import TeacherAPI from '@/api/teacher'

export default {
  name: 'CreateSubject',
  components: {
    TeacherNavbar
  },
  data() {
    // 自定义验证规则：总题数不能超过100
    const validateTotalQuestions = (rule, value, callback) => {
      const total = this.subjectForm.choiceQuestionCount + 
                   this.subjectForm.judgmentQuestionCount + 
                   this.subjectForm.fillQuestionCount;
      if (total > 100) {
        callback(new Error('总题数不能超过100题'));
      } else {
        callback();
      }
    };
    
    // 自定义验证规则：至少设置一种题型
    const validateAtLeastOneQuestionType = (rule, value, callback) => {
      const total = this.subjectForm.choiceQuestionCount + 
                   this.subjectForm.judgmentQuestionCount + 
                   this.subjectForm.fillQuestionCount;
      if (total === 0) {
        callback(new Error('至少需要设置一种题型'));
      } else {
        callback();
      }
    };
    
    return {
      submitting: false,
      subjectForm: {
        subjectName: '',
        choiceQuestionCount: 1,
        judgmentQuestionCount: 1,
        fillQuestionCount: 1,
        timeLimit: 60,
        choiceQuestionScore: 2,
        judgmentQuestionScore: 1,
        fillQuestionScore: 5
      },
      rules: {
        subjectName: [
          { required: true, message: '请输入科目名称', trigger: 'blur' },
          { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
        ],
        choiceQuestionCount: [
          { required: true, message: '请输入选择题数量', trigger: 'change' },
          { type: 'number', min: 0, max: 100, message: '选择题数量应在0-100之间', trigger: 'change' },
          { validator: validateTotalQuestions, trigger: 'change' },
          { validator: validateAtLeastOneQuestionType, trigger: 'change' }
        ],
        judgmentQuestionCount: [
          { required: true, message: '请输入判断题数量', trigger: 'change' },
          { type: 'number', min: 0, max: 100, message: '判断题数量应在0-100之间', trigger: 'change' },
          { validator: validateTotalQuestions, trigger: 'change' },
          { validator: validateAtLeastOneQuestionType, trigger: 'change' }
        ],
        fillQuestionCount: [
          { required: true, message: '请输入填空题数量', trigger: 'change' },
          { type: 'number', min: 0, max: 100, message: '填空题数量应在0-100之间', trigger: 'change' },
          { validator: validateTotalQuestions, trigger: 'change' },
          { validator: validateAtLeastOneQuestionType, trigger: 'change' }
        ],
        choiceQuestionScore: [
          { required: true, message: '请输入选择题分值', trigger: 'change' },
          { type: 'number', min: 0.5, max: 10, message: '选择题分值应在0.5-10分之间', trigger: 'change' }
        ],
        judgmentQuestionScore: [
          { required: true, message: '请输入判断题分值', trigger: 'change' },
          { type: 'number', min: 0.5, max: 10, message: '判断题分值应在0.5-10分之间', trigger: 'change' }
        ],
        fillQuestionScore: [
          { required: true, message: '请输入填空题分值', trigger: 'change' },
          { type: 'number', min: 0.5, max: 20, message: '填空题分值应在0.5-20分之间', trigger: 'change' }
        ],
        timeLimit: [
          { required: true, message: '请输入考试时长', trigger: 'change' },
          { type: 'number', min: 10, max: 180, message: '考试时长应在10-180分钟之间', trigger: 'change' }
        ]
      }
    }
  },
  computed: {
    // 计算科目总分和总题数
    summaryText() {
      const totalQuestions = this.subjectForm.choiceQuestionCount + 
                            this.subjectForm.judgmentQuestionCount + 
                            this.subjectForm.fillQuestionCount;
                            
      const totalScore = this.subjectForm.choiceQuestionCount * this.subjectForm.choiceQuestionScore +
                        this.subjectForm.judgmentQuestionCount * this.subjectForm.judgmentQuestionScore +
                        this.subjectForm.fillQuestionCount * this.subjectForm.fillQuestionScore;
                        
      return `总题数: ${totalQuestions} 题，总分: ${totalScore} 分`;
    }
  },
  methods: {
    // 提交表单
    submitForm() {
      this.$refs.subjectForm.validate(async (valid) => {
        if (valid) {
          this.submitting = true;
          try {
            const res = await TeacherAPI.createSubject(this.subjectForm);
            if (res.data.code === 200 && res.data.msg === 'success') {
              this.$message.success('科目创建成功');
              // 重置表单
              this.$refs.subjectForm.resetFields();
            } else {
              this.$message.error(res.data.message || '科目创建失败');
            }
          } catch (error) {
            console.error('创建科目失败:', error);
            this.$message.error('科目创建失败: ' + (error.response?.data?.message || error.message));
          } finally {
            this.submitting = false;
          }
        } else {
          console.log('表单验证失败');
          this.$message.error('请检查表单填写是否正确');
          return false;
        }
      });
    },
    
    // 重置表单
    resetForm() {
      this.$refs.subjectForm.resetFields();
    }
  }
}
</script>

<style scoped>
.create-subject {
  padding: 20px;
  background-color: #f8f9fa;
  min-height: calc(100vh - 40px);
}

.form-card {
  max-width: 800px;
  margin: 0 auto;
  border-radius: 10px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
  border: none;
}

.card-header {
  font-size: 1.3rem;
  font-weight: 500;
  color: #333;
  padding: 20px;
}

.section-title {
  margin: 20px 0 15px 0;
  padding-bottom: 10px;
  border-bottom: 1px solid #ebeef5;
  color: #333;
}

.subject-form {
  padding: 20px;
}

.summary-section {
  margin: 20px 0;
}

.form-actions {
  margin-top: 30px;
  text-align: center;
}

.form-actions .el-button {
  padding: 12px 30px;
  font-size: 16px;
}
</style>